package com.xiaomaoguai.fcp.pre.kepler.router.async.delay;

import com.xiaomaoguai.fcp.pre.kepler.router.async.RouterWorkPoolManager;
import com.xiaomaoguai.fcp.pre.kepler.router.async.WorkPool;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.api.HandlerContext;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.handlercontext.DefaultHandlerContext;
import com.xiaomaoguai.fcp.pre.kepler.router.lock.Spinlock;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.DelayQueue;

@Slf4j
public class DelayTask {

	private static final String threadName = "Router-DelayTask-1";
	private static Integer maxQueueSize = 1 << 16;
	private static Spinlock lock = new Spinlock();
	static {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						DefaultHandlerContext<?> hc = null;
						hc = delayQueue.take();
						if (hc != null) {
							String poolName = hc.getRouterInfo().getAsyncWorkPool();
							WorkPool<HandlerContext<?>> routerWorkPool = RouterWorkPoolManager.getPool(poolName);
							routerWorkPool.addTask(hc);
						}
					} catch (Exception e) {
						log.warn("DelayTask error", e);
					}
				}
			}
		});
		t.setName(threadName);
		t.setDaemon(Boolean.TRUE);
		t.start();
	}

	private static DelayQueue<DefaultHandlerContext<?>> delayQueue = new DelayQueue<DefaultHandlerContext<?>>();

	public static boolean addTask(DefaultHandlerContext<?> delay) {
		try {
			lock.lock();
			if(delayQueue.size()<maxQueueSize){
				log.info(delay.retryInfoString());
				return delayQueue.add(delay);
			}
			log.info(delay.retryInfoString()+"delayQueue size 已满，未能加入delayQueue,直接丢弃");	
			return Boolean.FALSE;
		} finally {
			lock.unlock();
		}
	}

}
